<?php
declare(strict_types=1);
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/7
 * Time: 2:13
 */

namespace ServerApp\lib\config;

use ServerApp\lib\memory\Chan;
use ServerApp\lib\memory\ChanFpm;
use ServerApp\lib\process\SProcess;
use ServerApp\lib\util\ServerHelper;
use WebApp\lib\config\Config;

/**
 *
 */
class LogConfig
{
    private $fp = null;
    private $path_arr = [];
    private $deamon = false;

    /**
     * @internal param $path
     * @internal param bool $deamon
     */
    public static function init(){
        if(self::$instance === null) {
            self::$instance = new self();
        }
    }

    private function create(){
        $pid = (new SProcess(function(){
            while (true){
                if ($data = Chan::getInstance('log')->pop()) {
                    fwrite($this->fp, $data);
                    if ($this->deamon === false) {
                        fwrite(STDOUT, $data);
                    }
                } else {
                    $this->initPath();
                    sleep(1);
                }
            }
        }))->start();
        $s = explode('\\', __CLASS__);
        file_put_contents(ServerHelper::getInstance()->getPidPath() . end($s) . __LINE__ . ".pid", $pid);

    }


    private function initPath() {
        $path = ServerHelper::getInstance()->getLogPath();
        $dir = dirname($path);
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
    }

    /**
     * @internal param $path
     * @internal param $deamon
     */
    private function __construct()
    {
        $this->initPath();
        if (ENV_PHP_FPM) {
            $this->deamon = true;
        } else {
            $this->deamon = Config::getConf('server.children.'.SERVER_NAME.'.daemonize') ??
                Config::getConf('server.setting.daemonize');
        }
//        if (ENV_PHP_FPM) {
//            $this->chan = ChanFpm::getInstance("log");
//        } else {
//            $this->chan = Chan::getInstance("log");
//            $this->create();
//            SProcess::signal(SIGCHLD, function () {
//                for(;;){
//                    $ret = SProcess::wait();
//                    if($ret){
//                        tracker(D, "-------xxxxxxx--------xxxxxxxxx-------pid={$ret['pid']}");
//                        if ($this->pid === $ret['pid']){
//                            $this->create();
//                        }
//                    }
//                }
//            });
//        }
    }

    public static $instance = null;

    /**
     * var LogConfig
     */
    public static function getInstance(): LogConfig
    {
        if (self::$instance === null) {
            die("log init first");
        }
        return self::$instance;
    }

    /**
     * @param $str
     */
    public function write($str){
        $path = ServerHelper::getInstance()->getLogPath();
//        if (!isset($this->path_arr[$path])) {
//            $this->path_arr[$path] = [
//                'is_file'=> is_file($path),
//                "time"=> time()
//            ];
//        }
//
//        if ($this->path_arr[$path]['is_file']) {
//            file_put_contents($path, $str, FILE_APPEND);
//        } else {
//            print_r($path, "not file");
//        }

        file_put_contents($path, $str, FILE_APPEND);
        if ($this->deamon === false) {
            fwrite(STDOUT, $str);
        }
    }
}